package com.app.view.component.scene 
{
	import flash.display.MovieClip;
	import flash.geom.Point;
	import flash.text.TextField;
	import flash.events.Event;
	
	import flash.display.SimpleButton;
	import flash.events.MouseEvent;
	
	import com.greensock.TweenLite;
	
	import org.component.Button;
	
	import com.peachcastle.core.Scene;
	import com.peachcastle.tools.Utils;
	import com.peachcastle.events.SeatEvent;
	
	import org.component.events.PageEvent;
	
	import com.app.AppFacade;
	
	import com.app.view.AppMediator;
	import com.app.view.manager.SoundManagerMediator;
	import com.app.view.manager.SceneManagerMediator;
	import com.app.view.manager.DialogManagerMediator;
	import com.app.view.component.common.Toolbar;
	import com.app.view.component.RoomMediator;
	import com.app.view.component.room.ShakerDiceItem;
	import com.app.view.component.room.PlayerSeats;
	import com.app.view.component.room.chips.ChipsManager;
	import com.app.view.component.room.exps.ExpsManager;
	import com.app.view.component.room.seat.Clock;
	import com.app.view.component.room.Chat;
	import com.app.view.component.room.expressions.ExpressionManager;
	
	import com.app.model.data.UserData;
	import com.app.model.data.LevelData;
	
	import com.peachcastle.tools.Assert;
	import com.peachcastle.debug.Log;
	
	public class RoomScene extends Scene 
	{
		public static const NAME:String = "RoomScene";
		public static const ASSEST_NAME:String = "RoomView";
		
		private static const NORMAL_POUR:int = 1;
		private static const FAILED_POUR:int = 0;
		
		private var _roomMediator:RoomMediator = null;
		
		private var _toolbar:Toolbar = null;
		
		private var _shaker:ShakerDiceItem = null;
		private var _playerSeats:PlayerSeats = null;
		private var _chipsManager:ChipsManager = null;
		private var _expManager:ExpsManager = null;
		private var _expressionManager:ExpressionManager = null;
		
		private var _mc_operate:MovieClip = null;
		private var _btn_stand:SimpleButton = null;
		private var _btn_go_hall:SimpleButton = null;
		private var _btn_check_result:Button = null;
		private var _btnExpression:SimpleButton = null;

		private var _mcGameTip:MovieClip = null;
		private var _mcPkGameTip:MovieClip = null;
		
		private var _userLevel:LevelData = null;
		private var _userData:UserData = null;
		
		private var _chat:Chat = null;

		public function RoomScene(swfUrlFunc:Function = null) 
		{
			super(NAME, swfUrlFunc, ["room", "expression"]);
		}
		
		public function setMediator(m:RoomMediator):void
		{
			_roomMediator = m;
		}
		
		override protected function enterScene():void 
		{
			super.enterScene();
			
			_roomMediator.sendNotification(AppMediator.ROOM_LOAD_OK);
		}
		
		override protected function showLoading(percent:Number = 0):void 
		{
			super.showLoading(percent);
			
			_roomMediator.sendNotification(AppMediator.ROOM_LOAD_PROGRESS, [percent]);
		}
		
		override protected function initializationView():void 
		{
			super.initializationView();

			super._assest = new (super.getLibByClass("room", ASSEST_NAME));
			Assert.notNull(super._assest, 'room');
			
			super._assest.cacheAsBitmap = true;
			Utils.stopClip(assest);

			//断言
			Assert.hasNot(assest, 'toolbar', 'room');
			Assert.hasNot(assest, 'shaker', 'room');
			Assert.hasNot(assest, 'paiList', 'room');
			Assert.hasNot(assest, 'chipsManager', 'room');
			Assert.hasNot(assest, 'expManager', 'room');
			Assert.hasNot(assest["chat"], 'expressionManager', 'room');
			Assert.hasNot(assest, 'chat', 'room');
			Assert.hasNot(assest, 'mc_game_tip', 'room');
			Assert.hasNot(assest, 'mc_pk_game_tip', 'room');
			Assert.hasNot(assest['mc_operate'], 'btn_stand', 'mc_operate');
			Assert.hasNot(assest['mc_operate'], 'btn_go_hall', 'mc_operate');
			Assert.hasNot(assest["chat"], 'btn_expression', 'room');
			
			_toolbar = new Toolbar(assest["toolbar"], _roomMediator);
			
			_shaker = new ShakerDiceItem(assest['shaker'], new Point(assest['paiList'].x, assest['paiList'].y));
			_playerSeats = new PlayerSeats(assest);
			_playerSeats.setPailistEndPoint(new Point(assest['shaker'].x, assest['shaker'].y));
			
			_chipsManager = new ChipsManager(assest["chipsManager"]);
			_expManager = new ExpsManager(assest["expManager"], true, assest.width, assest.height);
			_expressionManager = new ExpressionManager(assest["chat"]["expressionManager"], assest);
			
			_chat = new Chat(assest['chat'], _roomMediator);
			
			_mc_operate = assest['mc_operate'];
			_btn_stand = _mc_operate["btn_stand"];
			showStand(false);
			_btn_go_hall = _mc_operate["btn_go_hall"];
			
			_btn_check_result = new Button(assest['btn_see_result']);
			
			_btnExpression = assest["chat"]["btn_expression"];
			
			_mcGameTip = assest["mc_game_tip"];
			_mcPkGameTip = assest["mc_pk_game_tip"];
			showGameTip('init');
			
			_roomMediator.sendNotification(SceneManagerMediator.CURRENT_SCENE_REQUEST);
			_roomMediator.sendNotification(DialogManagerMediator.SET_STAGE_SIZE, [NAME, 760, 670]);
		}
		
		override protected function configureEventListeners():void 
		{
			super.configureEventListeners();

			_playerSeats.addEventListener(SeatEvent.SEAT_DOWN, onSendDown);
			_playerSeats.addEventListener(SeatEvent.SEAT_START_GAME, onStartGameClick);
			_playerSeats.addEventListener(SeatEvent.SEAT_BASE_POUR, onBasePourClick);
			_playerSeats.addEventListener(SeatEvent.SEAT_POUR, onPourClick);
			_playerSeats.addEventListener(SeatEvent.START_PK, onStartPk);
			
			_btn_go_hall.addEventListener(MouseEvent.CLICK, onGoHallClick);
			
			_btn_check_result.addEventListener(MouseEvent.CLICK, onCheckResult);
			
			_btnExpression.addEventListener(MouseEvent.CLICK, onShowExpression);
			_expressionManager.addEventListener(PageEvent.PAGE_SEND_FACE, onSendExpression);
		}
		
		override protected function removeEventListeners():void
		{
			super.removeEventListeners();
			
			_playerSeats.removeEventListener(SeatEvent.SEAT_DOWN, onSendDown);
			_playerSeats.removeEventListener(SeatEvent.SEAT_START_GAME, onStartGameClick);
			_playerSeats.removeEventListener(SeatEvent.SEAT_BASE_POUR, onBasePourClick);
			_playerSeats.removeEventListener(SeatEvent.SEAT_POUR, onPourClick);
			_playerSeats.removeEventListener(SeatEvent.START_PK, onStartPk);
			
			_btn_stand.removeEventListener(MouseEvent.CLICK, onStandClick);
			_btn_go_hall.removeEventListener(MouseEvent.CLICK, onGoHallClick);
			_btn_check_result.removeEventListener(MouseEvent.CLICK, onCheckResult);
			
			_btnExpression.removeEventListener(MouseEvent.CLICK, onShowExpression);
			_expressionManager.removeEventListener(PageEvent.PAGE_SEND_FACE, onSendExpression);
		}
		
		public function actionDices(dice:String):void
		{
			_roomMediator.sendNotification(SoundManagerMediator.PLAY, [SoundManagerMediator.SHAKER_DICE]);
			_shaker.play("start");
			TweenLite.delayedCall(2, _shaker.showValue, [dice.split(",")]);
		}
		
		private function onSendDown(e:SeatEvent):void
		{
			_roomMediator.sendNotification(RoomMediator.SIT_DOWN_REQUEST, [e.seatid]);
		}
		
		private function onStandClick(e:MouseEvent):void
		{
			showStand(false);
			_roomMediator.sendNotification(RoomMediator.STAND_REQUEST);
		}
		
		private function onGoHallClick(e:MouseEvent):void
		{
			showStand(false);
			_roomMediator.sendNotification(RoomMediator.GO_HALL_REQUEST);
		}

		private function onStartGameClick(e:SeatEvent):void
		{	
			_roomMediator.sendNotification(RoomMediator.START_GAME_REQUEST);
			playerSeats.setOperation(e.seatid, 'banker', 'startGame', false);
		}
		
		private function onBasePourClick(e:SeatEvent):void
		{
			_roomMediator.sendNotification(RoomMediator.BASE_POUR_REQUEST, [e.state, int(e.message)]);
			playerSeats.setOperation(e.seatid, 'playr', 'basePour', false);
		}
		
		private function onPourClick(e:SeatEvent):void
		{
			if (e.state)
			{
				var pais:String = _playerSeats.getPaijiuPosition(_roomMediator.selfSeatid);
				if (pais == '') 
				{
					_roomMediator.sendNotification(AppFacade.CLIENT_NOTICE, ["error_13"]);
					return;
				}
				_roomMediator.sendNotification(RoomMediator.POUR_REQUEST, [e.state, int(e.message), pais]);
			}else
			{	//弃牌
				_roomMediator.sendNotification(RoomMediator.POUR_REQUEST, [e.state, int(e.message), '']);
			}
			
			_playerSeats.changePaijiuStatus(_roomMediator.selfSeatid, false);
			playerSeats.setOperation(e.seatid, 'playr', 'callPour', false);
		}
		
		private function onStartPk(e:SeatEvent):void
		{
			var pais:String = _playerSeats.getPaijiuPosition(1);
			if (pais == '') 
			{
				_roomMediator.sendNotification(AppFacade.CLIENT_NOTICE, ["error_13"]);
				return;
			}
			_roomMediator.sendNotification(RoomMediator.PK_RESULT_REQUEST, [e.seatid, e.state, pais]);
			
			_playerSeats.changePaijiuStatus(_roomMediator.selfSeatid, false);
			playerSeats.setOperation(e.seatid, 'banker', 'pk', false);
		}
		
		private function onCheckResult(e:MouseEvent):void
		{
			Log.debug("onCheckResult");
			
			_roomMediator.sendNotification(RoomMediator.SHOW_LAST_RESULT_REQUEST);
		}

		/**
		 * 设置站起按钮
		 * @param	b
		 */
		public function showStand(b:Boolean = false):void
		{
			_btn_stand.visible = b;
			if (b)
			{
				_btn_stand.addEventListener(MouseEvent.CLICK, onStandClick);
			}else
			{
				_btn_stand.removeEventListener(MouseEvent.CLICK, onStandClick);
			}
		}
		
		override protected function removeLayer():void 
		{
			super.removeLayer();
			
			if (assest.parent)
			{
				assest.parent.removeChild(assest);
			}
		}
		
		public function showGameTip(status:String, msg:String = ''):void
		{
			switch(status)
			{
				case 'init':
					_mcGameTip.alpha = 0;
					_mcPkGameTip.alpha = 0;
					
					break;
					
				case 'start':
					_mcGameTip.alpha = 1;
					_mcGameTip.gotoAndStop(3);
					TweenLite.to(_mcGameTip, 3, { alpha:0 } );
					
					break;
				
				case 'over':
					_mcGameTip.alpha = 1;
					_mcGameTip.gotoAndStop(5);
					TweenLite.to(_mcGameTip, 3, { alpha:0 } );
					
					break;
					
				case "pk":
					_mcPkGameTip["username"].text = msg;
					_mcPkGameTip.alpha = 1;
					TweenLite.to(_mcPkGameTip, 3, { alpha:0 } );
					
					break;
			}
		}
		
		public function updateExp(seatid:int, increaseExp:int, isNewLevel:Boolean = false, levelData:LevelData = null):void
		{
			_expManager.updateExp(seatid, increaseExp, isNewLevel, levelData);
		}
		
		public function setRoomData(roomid:int, name:String, minPour:int):void
		{
			TextField(assest["mc_room_info"]["txt_room_id"]).text = String(roomid);
			TextField(assest["mc_room_info"]["txt_room_name"]).text = name;
			TextField(assest["mc_room_info"]["txt_room_min_pour"]).text = String(minPour);
		}
		
		public function setUserData(data:UserData, userLevel:LevelData):void
		{
			_userData = data;
			_userLevel = userLevel;
		}
		
		override public function addLayer():void 
		{
			super.addLayer();
			
			_toolbar.update(_userData, false, _userLevel);
		}
		
		public function writeChatText(str:String):void
		{
			_chat.writeText(str);
		}
		
		private function onShowExpression(e:MouseEvent):void
		{
			if (_expressionManager.isshow)
			{
				_expressionManager.hide();
				
				return;
			}
			_expressionManager.show();
		}
		
		private function onSendExpression(event:PageEvent):void
		{
			Log.debug("onSendExpression", event.id);
			_roomMediator.sendNotification(RoomMediator.EXPRESSION_REQUEST, [event.id]);
		}
		
		public function get playerSeats():PlayerSeats { return _playerSeats; }
		public function get chipsManager():ChipsManager { return _chipsManager; }
		public function get expressionManager():ExpressionManager { return _expressionManager; }
		public function get toolbar():Toolbar { return _toolbar; }
	}

}